package com.mymaxis.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.Vector;
import java.util.Collections;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;

import org.apache.axiom.om.util.UUIDGenerator;

import com.checkfree.isolutions.admin.ObjectId;
import com.checkfree.isolutions.customer.persist.Account;
import com.checkfree.isolutions.customer.persist.AccountHomeImpl;
import com.checkfree.isolutions.customer.persist.Merchant;
import com.checkfree.isolutions.customer.persist.MerchantHomeImpl;
import com.checkfree.isolutions.persist.PersistServer;
import com.checkfree.isolutions.statement.StatementSection;
import com.checkfree.isolutions.statement.persist.Statement;
import com.checkfree.isolutions.statement.persist.StatementBlob;
import com.checkfree.isolutions.statement.persist.StatementHome;
import com.checkfree.isolutions.statement.persist.StatementHomeImpl;
import com.checkfree.isolutions.streaming.IClassId;
import com.lowagie.text.pdf.PdfReader;
import com.mymaxis.domain.StmtSummaryInfo;
import com.mymaxis.ebppx.MyMaxisAppConnectionPoolServlet;
import com.mymaxis.ebppx.WsConstants;
import com.mymaxis.manager.DBConnectionManager;
import com.mymaxis.utils.DateUtil;





public class StmtDownloadService {

	
	public  List getListOfStatement(String strAccNo) throws Exception  {
	
		String merchant = "Maxis";
		String listOfStatementDetails="";
		List listOfStatement = new ArrayList();
		PersistServer.activate("Maxis");
		PersistServer.beginTransaction();
		TimeZone tz = TimeZone.getTimeZone("GMT+8:00");
        Calendar cal = Calendar.getInstance(tz);
        Date endDate = cal.getTime();
        //Get the start Date
        
        cal.add(Calendar.MONTH, -6);
        cal.set(Calendar.DATE, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        Date startDate = cal.getTime();
     

	
		////Sytem.out.println(startDate.toString());
		////Sytem.out.println(endDate.toString());
		
		try{
			Merchant cfiMerchant = MerchantHomeImpl.singleton().findByName(merchant);
			Account account = AccountHomeImpl.singleton().findByExternalKeyAndMerchant(strAccNo, cfiMerchant);
        
		
			Vector cfiStatements =  StatementHomeImpl.singleton().findByAccount(account,startDate,endDate);
			
			////Sytem.out.println("cfiStatements size :"+cfiStatements.size());
	
			
	
			for(int i=0;i<cfiStatements.size();i++){
			
				Statement statement = (Statement)cfiStatements.get(i);

				String formattedDate = new SimpleDateFormat("ddMMyyyy").format(statement.getDate());
				listOfStatementDetails = formattedDate +","+ statement.getInstanceId()+","+statement.getUserField1();
				listOfStatement.add(listOfStatementDetails);
				////Sytem.out.println("listOfStatement :"+listOfStatement);
			
			}
				Collections.reverse(listOfStatement);	
			 	PersistServer.commitTransaction();
		} catch (Throwable e) {
			
			if (PersistServer.transactionIsActive()) {
				try {
					PersistServer.rollbackTransaction();
				} catch (Exception er) {
				}
			}
			PersistServer.deactivate(); // clean up with deactivate
			////Sytem.out.println("Deactivate the transaction.....");
			
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			
			
			if (PersistServer.transactionIsActive()) {
				try {
					PersistServer.rollbackTransaction();
				} catch (Exception er) {
				}
			}
			PersistServer.deactivate(); // clean up with deactivate
			//Sytem.out.println("Deactivate the transaction.....");
			
		}
		return listOfStatement;
	}
	
	public DataHandler getStmtViaStmtId(String strStmtId, String strFileType) throws Exception {
	 
	
		PersistServer.activate("Maxis");
		//Sytem.out.println("Activating Persistent Server.....");
        
		PersistServer.beginTransaction();
        //Sytem.out.println("Starting the transaction.....");
        //Sytem.out.println("strStmtId : "+strStmtId);
        //Sytem.out.println("strFileType : "+strFileType);
        InputStream instr   = null;
        FileOutputStream outstr = null;
        DataHandler dataHandler = null;
   
        int stmtIdInt = Integer.parseInt(strStmtId);
        String fileExtension = "." + strFileType;
        String pdfFileName = strStmtId + fileExtension;
        File file = File.createTempFile(pdfFileName, fileExtension);
       
        file.deleteOnExit();
	 
	 try{
		 
		 if (WsConstants.PDF_FILE.equalsIgnoreCase(strFileType)) {
		 	StatementHome home = StatementHomeImpl.singleton();
	        ObjectId objectId = new ObjectId(IClassId.STATEMENT, stmtIdInt);
	        Statement cfiStatement   = home.findByObjectId(objectId);
	     //   cfiStatement.getStatementBlob();
	    //   StatementSection a =cfiStatement.getRootSection(true);
	    // a.getSection(name)
	    //   a.getSectionCount(name)
	     //  a.getRepeatSection(name, index)
	        outstr = new FileOutputStream(file);
	        
	        byte[] buffer = new byte[262144];
	        int size = 0;
	        
	        instr = cfiStatement.getExternalFormatData();
	      
   
	        //File w_File = new File("C:\\Documents and Settings\\mebuser\\Desktop\\a.pdf");
	       // StatementBlob s= cfiStatement.getStatementBlob();
	        //w_File.createNewFile();
	      //  InputStream input = resultSet.getBinaryStream("JVBERi0xLjQKJeLjz9MKNSAwIG9iaiA8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvVHlwZS9YT2JqZWN0L0xlbmd0aCAzMDQvQml0c1BlckNvbXBvbmVudCA4L0hlaWdodCAxMjQvQ29sb3JTcGFjZS9EZXZpY2VHcmF5L1N1YnR5cGUvSW1hZ2UvV2lkdGggOTM0Pj5zdHJlYW0KeJzt1sEJAwEUQsH03");
	       // InputStream w_BLOBStream =s.getRootSection().getB
	        
			while ((size  = instr.read(buffer, 0, buffer.length)) != -1) {
				outstr.write(buffer, 0, size);
			}
			instr.close();
			outstr.flush();
			outstr.close();
			dataHandler = new javax.activation.DataHandler(new FileDataSource(file));
	 	   	PersistServer.commitTransaction();
			//Sytem.out.println("Stoping the transaction.....");
			
		 }
	 }catch(Exception e){
			
			if (PersistServer.transactionIsActive()) {
				try {
					PersistServer.rollbackTransaction();
				} catch (Exception er) {
				}
			}
			PersistServer.deactivate(); // clean up with deactivate
			//Sytem.out.println("Deactivate the transaction.....");
	}finally{
		
		if (PersistServer.transactionIsActive()) {
			try {
				PersistServer.rollbackTransaction();
			} catch (Exception er) {
			}
		}
		PersistServer.deactivate(); // clean up with deactivate
		//Sytem.out.println("Deactivate the transaction.....");
		
	}
		 
	 
	
	 return dataHandler;
	
	}
	
	public StmtSummaryInfo getStmtSummaryViaStmtID(String strStmtId, String strFileType) throws Exception {
		
	
		PersistServer.activate("Maxis");
		//Sytem.out.println("Activating Persistent Server.....");
        
		PersistServer.beginTransaction();
        //Sytem.out.println("Starting the transaction.....");
        
        StmtSummaryInfo details = new StmtSummaryInfo();
        List lineDetails = new ArrayList();
        int stmtIdInt = Integer.parseInt(strStmtId);
        //Sytem.out.println("StmtIdInt :"+stmtIdInt);
		 try{
			 
			 	StatementHome home = StatementHomeImpl.singleton();
		        ObjectId objectId = new ObjectId(IClassId.STATEMENT, stmtIdInt);
		        Statement cfiStatement   = home.findByObjectId(objectId);
		        //Sytem.out.println("cfiStatement :"+cfiStatement);
		        if(cfiStatement !=null){
		        
		        	StatementSection rootSection = cfiStatement.getRootSection();
		            String overDueCharges = "";
		            String totalAmtDue = "";
		            String totalLineCharges	="";
		            String statementDate ="";
		            String totalServiceTax ="";
		            String GSTValue = "";
                 	String totalOtherChanges = "";
		            String phoneNumber = "";
		            String strPhoneNumber = "";
				
		            String totalAmount = "";
		            String lineDetailsHdr="";
		            String regPhoneNo = "";
		            String regOverDueCharges = "";
		            String regTotalAmtDue = "";
		            String regTotalAmt = "";
		            String discountRebates = "";
		            String totalCurrentCharges = "";
		            String simNo = "";
		            String regSimNo = "";
		        	DecimalFormat twoDForm = new DecimalFormat("#.##");
		            double totalLineChargesAmt =0.00;
		        
		            
		            
		            if(rootSection != null){
		            	
		        	  
		            	regTotalAmtDue = rootSection.getFieldText("TotalAmountDue");
		            	if(regTotalAmtDue !="" && regTotalAmtDue !=null){
		            	
		            		totalAmtDue = regTotalAmtDue.replaceAll("[\\\\RM]", "");
		            
		            		//Sytem.out.println("totalAmtDue :"+totalAmtDue);
		            	
		            		details.setTotalAmtDue(totalAmtDue);
		            	
		            	}
		            	regTotalAmt = rootSection.getFieldText("TotalAmount");
		            	if(regTotalAmt != "" && regTotalAmt != null){
		            	
		            		totalAmount =regTotalAmt.replaceAll("[\\\\RM]", "");
		            
		            		//Sytem.out.println("totalAmount :"+totalAmount);
		            		details.setTotalAmt(totalAmount);
		            	
		            	}
		        		//Sytem.out.println("totalAmtDue :"+totalAmtDue);
		        		//Sytem.out.println("statementDate :"+rootSection.getFieldText("StatementDate"));
		        		statementDate =rootSection.getFieldText("StatementDate");
		        		if(statementDate != null){
		        			
		        			Date date = new SimpleDateFormat("dd/MM/yyyy").parse(statementDate);
			        		String formattedDate = new SimpleDateFormat("ddMMyyyy").format(date);
			        		details.setStmtDate(formattedDate);
			        		
		        		}
		        		
		        		
				
		        		
		        		StatementSection AccountSummarySection = rootSection.getSection("AccountSummarySection");
		        		StatementSection servicesTaxSection = null;
		        		StatementSection GSTTaxSection = null;
		        	
		        		if(AccountSummarySection != null){
		        			details.setLineCountInd("M");
		        			StatementSection accountDetailsSection = AccountSummarySection.getSection("AccountDetailsSection");
		        			StatementSection totalCurrentChargesSection = AccountSummarySection.getSection("TotalCurrentChargesSection");
		        			if(totalCurrentChargesSection != null){
		        			totalCurrentCharges = totalCurrentChargesSection.getFieldText("TotalCurrentCharges");
		        			details.setTotalCurrentChanges(totalCurrentCharges);
		        			//Sytem.out.println("totalCurrentCharges :"+totalCurrentCharges);
		        			}
        					
		        			if(accountDetailsSection !=null){
		                        StatementSection discountRebatesSection = accountDetailsSection.getSection("DiscountRebatesSection");
		                        servicesTaxSection = accountDetailsSection.getSection("ServiceTaxSection");
		                        GSTTaxSection = accountDetailsSection.getSection("GSTSection");
		                        StatementSection otherChangesSection = accountDetailsSection.getSection("OtherChargesSection");
		        			
		        			
		        			
		        				if(discountRebatesSection != null)
		                            {
		                                long discountAndRebatesCount = discountRebatesSection.getSectionCount("RepeatSection");
		                                //System.out.println("discountAndRebatesCount :" + discountAndRebatesCount);
		                                for(int x = 0; x < discountAndRebatesCount; x++)
		                                {
		                                    StatementSection discountRebateRepeatSection = discountRebatesSection.getRepeatSection("RepeatSection", x);
		                                    discountRebates = discountRebateRepeatSection.getFieldText("Total");
		                                    details.setDiscountAndRebates(discountRebates);
		                                    //System.out.println("Discount Rebates :" + discountRebates);
		                                }

		                            }
		                            if(servicesTaxSection != null)
		                            {
		                                long serviceTaxSectionCount = servicesTaxSection.getSectionCount("RepeatSection");
		                                for(int x2 = 0; x2 < serviceTaxSectionCount; x2++)
		                                {
		                                    StatementSection serviceTaxRepeatSection = servicesTaxSection.getRepeatSection("RepeatSection", x2);
		                                    totalServiceTax = serviceTaxRepeatSection.getFieldText("Total");
		                                    details.setServiceTax(totalServiceTax);
		                                    details.setTaxType(WsConstants.TAX_TYPE_SVT);
		                                    //System.out.println("Total ServiceTax :" + totalServiceTax);
		                                }

		                            }
		                            
		                            if(GSTTaxSection != null)
		                            {
	                                    totalServiceTax = GSTTaxSection.getFieldText("TotalTotal");
	                                    details.setServiceTax(totalServiceTax);
	                                    details.setTaxType(WsConstants.TAX_TYPE_GST);
	                                   //System.out.println("Total ServiceTax :" + totalServiceTax);
		                            }
		                            if(otherChangesSection != null)
		                            {
		                                long otherChangesSectionCount = otherChangesSection.getSectionCount("RepeatSection");
		                                for(int x3 = 0; x3 < otherChangesSectionCount; x3++)
		                                {
		                                    StatementSection otherChangesRepeatSection = otherChangesSection.getRepeatSection("RepeatSection", x3);
		                                    totalOtherChanges = otherChangesRepeatSection.getFieldText("Total");
		                                    details.setOtherChanges(totalOtherChanges);
		                                    System.out.println("Total other Changes :" + totalOtherChanges);
		                                }

		                            }
		                        }
		        					
		        					
		        					
		        					StatementSection DetailsOfChargesSection = rootSection.getSection("DetailsOfChargesSection");
		        					if(DetailsOfChargesSection != null)
		    		        		{
		    		        			long phoneNumberSectionCount =DetailsOfChargesSection.getSectionCount("PhoneNumberSection");
		    		        			//Sytem.out.println("phoneNumberSectionCount :"+phoneNumberSectionCount);
		    		        			
//		    		        			if(phoneNumberSectionCount > 1){
//		    		        			 
//		    		        				 details.setLineCountInd("M");
//		    		        				
//		    		        			}
		    		        			for(int i=0;i<phoneNumberSectionCount;i++){
		    		        			   
		    		        			    StatementSection phoneNumberSection =DetailsOfChargesSection.getRepeatSection("PhoneNumberSection", i);
		    		        				//Sytem.out.println("phoneNumberSection :"+phoneNumberSection);
		    		        				phoneNumber =phoneNumberSection.getFieldText("PhoneNumber");
		    		        				

		    		        			    //Sytem.out.println("PHOME NUMBER :"+phoneNumber);
		    		        				regPhoneNo = phoneNumber.startsWith(":") ? phoneNumber.substring(1) : phoneNumber;
		    		        				//Sytem.out.println("Phone No :"+regPhoneNo);
		    		        			
		    		        				strPhoneNumber =regPhoneNo.replaceAll("[\\\\(\\\\:\\\\)]", "");	
		    		        				//Sytem.out.println("strPhoneNumber "+strPhoneNumber);
		    		        				
		    		        				regSimNo = phoneNumberSection.getFieldText("SimNumber");
		    		        				//regSimNo =regSimNo.trim();
		    		        				
		    		        				simNo = regSimNo.replaceAll(":","");
		    		        				//Sytem.out.println("SimNo :"+simNo);
		    		        				
		    		        				StatementSection itemWithRebateSection = phoneNumberSection.getSection("ItemWithRebateSection").getSection("TotalLineChargesSection");
		    		        			    totalLineCharges = itemWithRebateSection.getFieldText("Total");
		    		        			   
		    		        				lineDetailsHdr =strPhoneNumber+","+simNo+","+totalLineCharges;
		    		        				lineDetails.add(lineDetailsHdr);
		    		        			}
		    		        			
		    		        			details.setLineDetail(lineDetails);
		    		        			//NumberUtil.fromCentsToRinggit(totalChanges);
		    		        		
		    		        			  
		    		        		

		    		        			//details.setCurrentAmt(twoDForm.format(totalLineChargesAmt));
		    		        			
		    		        		
		        					
		        					
		        				}
		        			
		        			//Sytem.out.println("Account summanry not null");
		        			
		        			
		        		}else{
		        			//Sytem.out.println("Account equal null");
		        			StatementSection DetailsOfChargesSection = rootSection.getSection("DetailsOfChargesSection");
		        			if(DetailsOfChargesSection != null)
    		        		{
		        				details.setLineCountInd(WsConstants.LINE_COUNT_SINGLE);
    		        			long phoneNumberSectionCount =DetailsOfChargesSection.getSectionCount("PhoneNumberSection");
    		        			//Sytem.out.println("phoneNumberSectionCount :"+phoneNumberSectionCount);
    		        			for(int i=0;i<phoneNumberSectionCount;i++){
    		        			
    		        			    StatementSection phoneNumberSection =DetailsOfChargesSection.getRepeatSection("PhoneNumberSection", i);
    		        				//Sytem.out.println("phoneNumberSection :"+phoneNumberSection);
    		      
    		        				phoneNumber =phoneNumberSection.getFieldText("PhoneNumber");
    		        				//Sytem.out.println("Phone Numnber :"+phoneNumber);
    		        				regPhoneNo = phoneNumber.startsWith(":") ? phoneNumber.substring(1) : phoneNumber;
    		        				
    		        				strPhoneNumber =regPhoneNo.replaceAll("[\\\\(\\\\:\\\\)]", "");
    		        				//Sytem.out.println("strPhoneNumber "+strPhoneNumber);
    		        				
    		        				regSimNo = phoneNumberSection.getFieldText("SimNumber");
    		        				simNo = regSimNo.replaceAll(":","");
    		        				//Sytem.out.println("SimNo :"+simNo);
    		        				
    		        				StatementSection itemWithRebateSection = phoneNumberSection.getSection("ItemWithRebateSection");
    		        				//Sytem.out.println("itemWithRebateSection :"+itemWithRebateSection);
    		        				if(itemWithRebateSection !=null){
    		        					
    		        					StatementSection TotalLineChargesSection = itemWithRebateSection.getSection("TotalLineChargesSection");
    		        					if(TotalLineChargesSection != null){
    		        						
    		        					totalLineCharges = TotalLineChargesSection.getFieldText("Total");
    		        					//totalLineChargesAmt += Double.parseDouble(totalLineCharges);
    		        					//Sytem.out.println("TotalLineCharges :"+totalLineCharges);
    		        					}
    		        				}
    		        				//Sytem.out.println("itemWithRebateSection :"+itemWithRebateSection);
    		        				
    		        				if(itemWithRebateSection !=null){
    		        					StatementSection discountAndRebatesSection = itemWithRebateSection.getSection("DiscountAndRebatesSection");
    		        				    
    		        				     if(discountAndRebatesSection != null){
    		        				    	long  discountAndRebatesCount = discountAndRebatesSection.getSectionCount("RepeatSection");
    		        				    	//Sytem.out.println("discountAndRebatesCount :"+discountAndRebatesCount);
    		        				    	for(int x = 0;x<discountAndRebatesCount;x++){
    		        				    		
    		        				    		StatementSection discountRebateRepeatSection =discountAndRebatesSection.getRepeatSection("RepeatSection", x);
    		        				    		discountRebates = discountRebateRepeatSection.getFieldText("Total");
    		        			   				//Sytem.out.println("discountRebates :"+discountRebates);
    		        				    		details.setDiscountAndRebates(discountRebates);
	    		        				    	//Sytem.out.println("Discount Rebates :"+discountRebates);
    		        				    		
    		        				    	}
    		        				    	
    		        				    }
    		        				}
    		        				 
    		        			    
    		        				
    		        				if(itemWithRebateSection != null){
    		        					StatementSection serviceTaxSection = itemWithRebateSection.getSection("ServiceTaxSection");
    		        					
    		        			        ////Sytem.out.println("TOTAL SERIVCETAX SECTION COUNT :"+serviceTaxSection.getSectionCount("Total"));
    		        					if(serviceTaxSection != null){
    		        						//long serviceTaxSectionCount = serviceTaxSe
    		        						long serviceTaxSectionCount = serviceTaxSection.getSectionCount("RepeatSection");
    		        						for(int x2 = 0;x2 < serviceTaxSectionCount;x2++){
    		        							StatementSection serviceTaxRepeatSection =serviceTaxSection.getRepeatSection("RepeatSection", x2);
    		        							totalServiceTax = serviceTaxRepeatSection.getFieldText("Total");
    		        							details.setServiceTax(totalServiceTax);
    		        							details.setTaxType(WsConstants.TAX_TYPE_SVT);
    		        							//Sytem.out.println("Total ServiceTax :"+totalServiceTax);
    		        						}
    		        						
    		        						
    		        					} else {
    		        						StatementSection totalLineChargeSection = itemWithRebateSection.getSection("TotalLineChargesSection");
    		        							if(totalLineChargeSection != null){
    		        								GSTValue = totalLineChargeSection.getFieldText("GST");
    		        								details.setServiceTax(GSTValue);
    		        								details.setTaxType(WsConstants.TAX_TYPE_GST);
    		        						}
    		        					}
    		        					
    		        					
    		        					
    		        					
    		        				}
									if(itemWithRebateSection != null){
    		        					StatementSection otherChangesSection = itemWithRebateSection.getSection("OtherChargesAndCreditSection");
    		        					if(otherChangesSection != null){
		        						 
		        						 long otherChangesSectionCount = otherChangesSection.getSectionCount("RepeatSection");
		        						 for(int x3 = 0;x3 < otherChangesSectionCount;x3++){
	 		        							StatementSection otherChangesRepeatSection =otherChangesSection.getRepeatSection("RepeatSection", x3);
	 		        							totalOtherChanges = otherChangesRepeatSection.getFieldText("Total");
	 		        							details.setOtherChanges(totalOtherChanges);
	 		        							System.out.println("Total other Changes :"+totalOtherChanges);
	 		        						
	 		        					}
		        						 
		        						 
		        					 }
    		        				}
    		        				lineDetailsHdr =strPhoneNumber+","+simNo+","+totalLineCharges;
    		        				lineDetails.add(lineDetailsHdr);
    		        			}
    		        
    		        			//Sytem.out.println("lineDetails :"+lineDetails);
    		        			details.setLineDetail(lineDetails);
    		        			
    		        		}
        					
		        			
		        		}
		        		
		        	 //Sytem.out.println("LIST :"+lineDetails);
		        	
		        	 }
		            
		        	 StatementSection summarySection=cfiStatement.getRootSection().getSection("SummarySection");
		        	 if(summarySection != null){
		        		 
		        	
		        		regOverDueCharges =summarySection.getFieldText("OverDueCharges");
		        		
		        		if(regOverDueCharges != null && regOverDueCharges !=""){
		        		
		        			//Sytem.out.println("regOverDueCharges :"+overDueCharges);
		        			try{
		        			overDueCharges = regOverDueCharges.replaceAll("[\\\\RM]", "");
		        			//Sytem.out.println("overDueCharges :"+overDueCharges);
 		        			//details.setTotalLineChrgs(twoDForm.format(totalLineChargesAmt));
		        			details.setOverDue(overDueCharges);
		        			}catch(Exception e){
		        				e.printStackTrace();
		        			}
		        		}
		        	 }
		 }
		        	 
			   
		        
		     	PersistServer.commitTransaction();
				//Sytem.out.println("Stoping the transaction.....");
		 }catch(Exception e){
			 e.printStackTrace();
				if (PersistServer.transactionIsActive()) {
					try {
						PersistServer.rollbackTransaction();
					} catch (Exception er) {
					}
				}
				PersistServer.deactivate(); // clean up with deactivate
				//Sytem.out.println("Deactivate the transaction.....");
			 
		 }finally{
			 
				if (PersistServer.transactionIsActive()) {
					try {
						PersistServer.rollbackTransaction();
					} catch (Exception er) {
					}
				}
				PersistServer.deactivate(); // clean up with deactivate
				//Sytem.out.println("Deactivate the transaction.....");
		 }
		return details;
		
		
	}
	public String getMerchant(){
        // Get Merchant Name
        String merchantName = "";
        try {
            com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();

            if (appCfg.hasProperty("MerchantName")){
                merchantName = appCfg.getProperty("MerchantName");
            }
        }
        catch (Exception e) {
        	//Sytem.out.println(e);
        }
        return merchantName;
	}
	
	public String getPDFStatementURLViaStatementID(String stmtID){
		String pdfUrl = null;
		try {
			
			PersistServer.activate("Maxis");
			PersistServer.beginTransaction();
			
			com.checkfree.isolutions.property.Properties appCfg = com.checkfree.isolutions.property.PropertiesConfig.getApplicationSettings();
			if (!appCfg.hasProperty("pdf_url")) {
				throw new IllegalArgumentException("no pdf url!");
			}
				String url = appCfg.getProperty("pdf_url");
			if (appCfg.hasProperty("passphrase") == false) {
				throw new IllegalArgumentException("no passphrase setting");
			} 
				String passphrase = appCfg.getProperty("passphrase");
			if (appCfg.hasProperty("time_out") == false) {
				throw new IllegalArgumentException("no time_out setting");
			} 
				long timeout = appCfg.getProperty("time_out", 3600000);

	    	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	    	Date requestDate = Calendar.getInstance().getTime();
	    	
	    	Date expireDate = new Date(requestDate.getTime() + timeout); 
	     	
	    	String token = sdf.format(requestDate)  + UUIDGenerator.getUUID(); 
	    	String parameter = com.mymaxis.utils.EncryptionHelper.encrypt(stmtID, passphrase);
	    	String downloaded = "N";
	    	//Sytem.out.println("Parameter :"+parameter);
	    	
			insertStatementDownloadInfo(stmtID,token,DateUtil.formatDate(requestDate),DateUtil.formatDate(expireDate),downloaded);
			//Sytem.out.println("pdfUrl before encode :"+url +"param="+parameter+"&token="+token);
			pdfUrl = url +"param="+URLEncoder.encode(parameter,"UTF-8")+"&token="+URLEncoder.encode(token,"UTF-8");
			//Sytem.out.println("pdfUrl :"+pdfUrl);
			PersistServer.commitTransaction();
			PersistServer.deactivate();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			if (PersistServer.transactionIsActive()) {
				try {
					PersistServer.rollbackTransaction();
				} catch (Exception er) {
				}
			}
			PersistServer.deactivate(); // clean up with deactivate
			//Sytem.out.println("Deactivate the transaction.....");
		}
    	return pdfUrl;
		
	}
	
	public static void insertStatementDownloadInfo(String stmtID, String token, String requestDate, String expireDate, String Downloaded) throws Exception{
	   	 Connection connection = null;

	   	 try {
				connection = AcctDetails.getDbConnection();
//	   		 	connection =  getConnectionTest();
				//Sytem.out.println("connection :"+connection);

	            if(connection!=null){
					insertStatementDownloadInfo(connection, stmtID, token, requestDate, expireDate, Downloaded);
	            }
	           
	            //AcctDetails.freeDbConnection(connection);
	            //Sytem.out.println("connection2 :"+connection);
	            
	        }
	        catch(Exception e) {
	            throw new Exception("Error logging inserting account details table : " + e);
	        }finally{
	        	if(connection != null){
	        		AcctDetails.freeDbConnection(connection);
	        	}
	        }

	    }
	    public static void insertStatementDownloadInfo(Connection connection, String stmtID, String token, String requestDate, String expireDate, String Downloaded) throws Exception {
	   	 
	    	PreparedStatement pstmt = null;
	        try {
	            if(connection!=null){
	                pstmt = connection.prepareStatement("INSERT INTO TBL_STATEMENT_DOWNLOAD (STMTID, TOKEN, REQUESTDATE, EXPIREDATE, DOWNLOAD) "
	                		+ "VALUES (?,?,TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS'),TO_DATE(?, 'DD/MM/YYYY HH24:MI:SS'),?)");
	                pstmt.setString(1,stmtID);
	                pstmt.setString(2,token);
	                pstmt.setString(3,requestDate);
	                pstmt.setString(4,expireDate);
	                pstmt.setString(5, Downloaded);
	                pstmt.execute();

					if (pstmt != null) {
						pstmt.close();
					}
	            }
	        }
	        catch(Exception e) {
	            throw new Exception("Error logging inserting statement_download table : " + e);
	        }finally{
	        	
	        	if(pstmt != null){
	        		pstmt.close();
	        	}
	        	
	        	
	        }
	    }
	

	
}
